import Taro from '@tarojs/taro';
import config from '../common/config';
import request from '../common/request';
import { saveToken } from '../common/wx';

// 查看微信头像等非本地服务图像
export function headimgHD(imageUrl) {
  if (imageUrl.indexOf('vi_32') < 0) {
    return imageUrl;
  }
  imageUrl = imageUrl.split('/'); //把头像的路径切成数组
  //把大小数值为 46 || 64 || 96 || 132 的转换为0
  if (
    imageUrl[imageUrl.length - 1] &&
    (imageUrl[imageUrl.length - 1] == 46 ||
      imageUrl[imageUrl.length - 1] == 64 ||
      imageUrl[imageUrl.length - 1] == 96 ||
      imageUrl[imageUrl.length - 1] == 132)
  ) {
    imageUrl[imageUrl.length - 1] = 0;
  }
  imageUrl = imageUrl.join('/'); //重新拼接为字符串
  return imageUrl;
}
// 替换图片链接
export function imagePath(path) {
  if (!path) {
    return;
  }
  if (path.indexOf('http') > -1) {
    return path;
  }
  return config.apiPrefix + path;
}
// 按长度截取字符串长度
export function substr(str, length) {
  if (!str || !length) {
    return str;
  }

  return str.length > length ? str.substring(0, length) + '...' : str;
}

// 转换时间格式
export function formatTimeZh(date, flag) {
  if (!date) {
    return;
  }
  date = new Date(date);

  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var hour = date.getHours();
  var minute = date.getMinutes();
  // var formatNumber = function(n) {
  //   n = n.toString();
  //   return n[1] ? n : '0' + n;
  // };
  var dateList = [year, month, day].map(formatNumber);
  return (
    dateList[0] +
    (flag || '年') +
    dateList[1] +
    (flag || '月') +
    dateList[2] +
    (flag ? '' : '日') +
    ' ' +
    [hour, minute].map(formatNumber).join(':')
  );
}
// 转化日期格式
export function formatTimeDate(date) {
  if (!date) {
    return;
  }
  date = new Date(date);

  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();

  var dateList = [year, month, day].map(formatNumber);
  return dateList[0] + '-' + dateList[1] + '-' + dateList[2];
}
// 转化月份格式
export function formatTimeMoth(date) {
  if (!date) {
    return;
  }
  date = new Date(date);

  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();

  var dateList = [year, month, day].map(formatNumber);
  return dateList[0] + '-' + dateList[1];
}
// 转化时间格式
export function formatTimeTime(date) {
  if (!date || date < 0) {
    return;
  }
  date = new Date(date);

  var hour = date.getHours();
  var minute = date.getMinutes();
  var seconds = date.getSeconds();

  return [hour, minute, seconds].map(formatNumber).join(':');
}
// 转换单位数为双位数：9 -> 09
export function formatNumber(n) {
  n = n.toString();
  return n[1] ? n : '0' + n;
}

// 延迟函数
export function sleep(time) {
  return new Promise(resolve => setTimeout(resolve, time));
}

// 获取图片链接
export function getImagePath(fileId, fileCode) {
  return (
    config.filePrefix +
    `/file/file/download?fileId=${fileId}&fileCode=${fileCode}&Client=${
      config.client
    }&Authorization=${Taro.getStorageSync('token')}`
  );
}
export const deadlineTime = (time)=>{
  let diff = time - new Date().getTime();
  if (!diff || diff < 0) {
    return `0天0时0分`;
  }
  let baseTime = 24 * 60 * 60 * 1000; //天
  const day = Math.floor(diff / baseTime);
  diff = diff % baseTime;
  baseTime = baseTime / 24;
  const hour = Math.floor(diff / baseTime);
  diff = diff % baseTime;
  baseTime = baseTime / 60;
  const minute = Math.floor(diff / baseTime);

  return (`${day}天${hour}时${minute}分`);
}

// 计算倒计时
export function countdownTime(time, mode) {
  let diff = time - new Date().getTime();
  if (!diff || diff < 0 || (mode === 1 && diff >= 3 * 24 * 60 * 60 * 1000)) {
    return;
  }
  let baseTime = 24 * 60 * 60 * 1000; // 天基数
  const day = Math.floor(diff / baseTime);
  diff = diff % baseTime;
  baseTime = baseTime / 24;
  let hour = Math.floor(diff / baseTime);
  diff = diff % baseTime;
  baseTime = baseTime / 60;
  const minute = Math.floor(diff / baseTime);
  diff = diff % baseTime;
  baseTime = baseTime / 60;
  const seconds = Math.floor(diff / baseTime);

  if (mode == 1) {
    hour += day * 24;

    return [hour, minute, seconds]
      .map(formatNumber)
      .join('')
      .split('');
  }
  return `${day}天${hour}时${minute}分`;
}

// 已经过去多长时间
export function pastTime(time) {
  return diffTime(new Date().getTime(),time);
}

export function diffTime(startTime=new Date().getTime(),endTime) {
  let diff = startTime -endTime;
  // if (!diff || diff < 0 || (mode === 1 && diff >= 3 * 24 * 60 * 60 * 1000)) {
  //   return;
  // }
  let baseTime = 24 * 60 * 60 * 1000; // 天基数
  const day = Math.floor(diff / baseTime);
  diff = diff % baseTime;
  baseTime = baseTime / 24;
  let hour = Math.floor(diff / baseTime);
  diff = diff % baseTime;
  baseTime = baseTime / 60;
  const minute = Math.floor(diff / baseTime);
  diff = diff % baseTime;
  baseTime = baseTime / 60;
  const seconds = Math.floor(diff / baseTime);

  hour += day * 24;
  return [hour, minute, seconds]
    .map(formatNumber)
    .join(':')
    .split('');
  // return `${day}天${hour}时${minute}分`;
}

// 用于是否要跳到绑定或者是认证页面
//
export function preRequest(fun) {
  const { certifiedStatus=2 } = Taro.getStorageSync('user') || {};
  // 去中转页面
  if (certifiedStatus !== 1) {
    Taro.redirectTo({
      url: '/pages/login/index',
    });
    return;
  }
  // 待认证时刻
  if (certifiedStatus === 4) {
    // 去查下接口，看有没有审核通过
    request({method : 'GET', tartget: 'userInfoQuery', data: {} }).then((data)=>{
      if (data.success) {
        if (data.model.certifiedStatus === 1) {
          saveToken(data.model);
          fun();
        } else {
          // 继续等待
          Taro.redirectTo({
            url: '/pages/login/index',
          });
        }
      }
    });
  }
  fun();
}

// 在这里判断路由的权限校验
export function navigateTo(option) {
  const { certifiedStatus=2 } = Taro.getStorageSync('user') || {};

  // 在查看详情已注册就可以查看详情了（特殊处理）
  if (option.url.includes('indexDetail') && certifiedStatus === 3) {
    Taro.navigateTo(option);
    return;
  }
  // 去中转页面
  if (certifiedStatus !== 1) {
    Taro.navigateTo({
      url: '/pages/login/index',
    });
    return;
  }
  // 待认证时刻
  if (certifiedStatus === 4) {
    // 去查下接口，看有没有审核通过
    request({method : 'GET', tartget: 'userInfoQuery', data: {} }).then((data)=>{
      if (data.success) {
        if (data.model.certifiedStatus === 1) {
          saveToken(data.model);
          Taro.navigateTo(option);
        } else {
          // 继续等待
          Taro.redirectTo({
            url: '/pages/login/index',
          });
        }
      }
    });
  }
  Taro.navigateTo(option);
}
